package com.example.demo.proxy;

import cn.hankchan.redis.sdk.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author hankChan
 *         2018/2/6 0006.
 */
@Service("httpRequestControlProxy")
public class HttpRequestControlProxy {

    @Autowired
    RedisDistributedLock redisDistributedLock;

    public String allowOneHandleOnSameTime(String key, String parameters, String requestId) {
        boolean lock = redisDistributedLock.lock(key, requestId, 10000);
        System.out.println(lock + "," + requestId);
        if(lock) {
            try {
                Thread.sleep(3000);
                return "操作成功:" + new Date().getTime();
            } catch (Exception e) {
                return "操作失败:" + e.getMessage();
            } finally {
                // 调用成功必须主动释放锁,如果没有主动释放,将在指定时效后才会自动释放锁
                redisDistributedLock.unlock(key, requestId);
            }
        } else {
            return "操作正在执行中,请勿重复执行操作!";
        }
    }

    /**
     * 每分钟只允许一次调用
     * @param key 请求方对该接口方法的唯一标识
     * @param parameters 请求参数列表
     * @param requestId 请求唯一标识
     * @return 调用结果
     */
    public String allowOneRequestPerMinutes(String key, String parameters, String requestId) {
        if(redisDistributedLock.lock(key, requestId, 60000)) {
            // 调用成功不主动释放锁，而是等待锁过期!
            return "调用成功:" + new Date().getTime();
        }
        return "请勿频繁刷新调用!";
    }

}
